package vip.xumy.picture.ctrl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import vip.xumy.core.exception.CoreException;
import vip.xumy.core.pojo.com.AjaxResponse;
import vip.xumy.core.pojo.com.PageResponse;
import vip.xumy.picture.pojo.Picture;
import vip.xumy.picture.service.PictureService;

/**
 * Do not use for any commercial purposes without permission
 * 
 * @author: mengyxu
 * @date: 2021年12月31日
 */

@RestController
@RequestMapping("picture")
public class PictureController {
	@Autowired
	private PictureService pictureService;

	@GetMapping
	public PageResponse<Picture> list(Picture example, HttpServletRequest request) {
		PageResponse<Picture> rsp = new PageResponse<>();
		String userId = MyUserController.getUserId(request);
		if (userId == null) {
			rsp.setRows(new ArrayList<Picture>());
			rsp.setTotal(0L);
		} else {
			example.setUser(userId);
			Page<Picture> pages = PageHelper.startPage(example.getPage(), example.getSize());
			List<Picture> list = pictureService.list(example);
			rsp.setRows(list);
			rsp.setTotal(pages.getTotal());
		}
		return rsp;
	}

	@PostMapping
	public AjaxResponse save(MultipartFile file, HttpServletRequest request) throws CoreException {
		String userId = MyUserController.getUserId(request);
		if (userId == null) {
			return AjaxResponse.failed("请先登录");
		}
		pictureService.save(file, userId);
		return new AjaxResponse(true, "上传成功");
	}

	@PutMapping
	public AjaxResponse update(@RequestBody Picture picture) throws CoreException {
		pictureService.update(null, picture);
		return new AjaxResponse(true, "更新成功");
	}

	@PostMapping("img")
	public AjaxResponse updateImg(MultipartFile file, Picture picture) throws CoreException {
		pictureService.update(file, picture);
		return new AjaxResponse(true, "更新成功");
	}

	@DeleteMapping
	public AjaxResponse delete(@RequestBody Picture picture) throws CoreException {
		pictureService.delete(picture);
		return new AjaxResponse(true, "删除成功");
	}

}
